import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_picking_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/stock_picking.dart';
import 'package:flutter_admin/pages/odoo/material/workshop_picking/batch_out.dart';
import 'package:flutter_admin/pages/odoo/material/workshop_picking/product_odo_data.dart';
import 'package:flutter_admin/pages/odoo/material/workshop_picking/production_order_query.dart';
import 'package:flutter_admin/pages/odoo/material/workshop_picking/workshop_picking_dialog.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:flutter_admin/pages/odoo/stock_picking/stock_production_list.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class WorkshopPickingList extends StatefulWidget {
  WorkshopPickingList({Key? key}) : super(key: key);
  @override
  _WorkshopPickingListListState createState() =>
      _WorkshopPickingListListState();
}

class _WorkshopPickingListListState extends State<WorkshopPickingList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockPicking stockPicking = StockPicking();
  List<StockPicking> selectedList = [];

  //工厂名称
  List<SelectOptionVO> locationIdList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];

  DateFormat format = DateFormat('yyyy-MM-dd');

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    stockPicking.createDateStart = Utils.getDate();
    stockPicking.createDateEnd = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      this.workshopIdList = await DynamicDataApi.getModelSelect(
          // active: false,
          model: "hr.department",
          name: "complete_name",
          key: 'parent_id',
          operator: "!=",
          val: null);
    } else {
      locationIdList = await DynamicDataApi.getModelSelect(
          active: false,
          model: "stock.location",
          name: "complete_name",
          key: 'workshop_id',
          val: int.parse(userInfo.deptId!),
          key2: 'comment',
          val2: 'XBK');
      stockPicking.workshopId = userInfo.deptId;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '出库开始日期',
            value: stockPicking.createDateStart,
            lastDate: isNotBlank(stockPicking.createDateEnd)
                ? format.parse(stockPicking.createDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockPicking.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              stockPicking.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '出库结束日期',
            value: stockPicking.createDateEnd,
            firstDate: isNotBlank(stockPicking.createDateStart)
                ? format.parse(stockPicking.createDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockPicking.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              stockPicking.createDateEnd = v;
            },
          ),
          userInfo.major != null
              ? CrySelect(
                  width: 280,
                  label: '生产车间',
                  dataList: workshopIdList,
                  value: stockPicking.workshopId,
                  onSaved: (v) => {stockPicking.workshopId = v},
                  onChange: (v) async {
                    if (stockPicking.workshopId != v) {
                      formKey.currentState!.save();
                      stockPicking.workshopId = v;
                      stockPicking.locationId = null;
                      try {
                        locationIdList = await DynamicDataApi.getModelSelect(
                            active: false,
                            model: "stock.location",
                            name: "complete_name",
                            key: 'workshop_id',
                            val: int.parse(v),
                            key2: 'comment',
                            val2: 'XBK');
                      } catch (e) {
                        locationIdList = [];
                      }
                      setState(() {});
                    }
                  },
                )
              : CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
          CrySelect(
            label: '库房',
            width: 380,
            dataList: locationIdList,
            value: stockPicking.locationId,
            onSaved: (v) => {stockPicking.locationId = v},
          ),
          CryInput(
            width: 160,
            label: '物料编码',
            value: stockPicking.productCode,
            onSaved: (v) {
              stockPicking.productCode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物料名称',
            value: stockPicking.productName,
            onSaved: (v) {
              stockPicking.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('出库单号')),
        DataColumn(label: Text('批次号')),
        DataColumn(label: Text('操作人')),
        DataColumn(label: Text('操作时间')),
        DataColumn(label: Text('来源库房')),
        DataColumn(label: Text('目标库房')),
        DataColumn(label: Text('出库类型')),
        DataColumn(label: Text('领料生产单号')),
      ],
      getCells: (m) {
        StockPicking stockPicking = StockPicking.fromMap(m);
        return [
          DataCell(Text(stockPicking.name ?? '--')),
          DataCell(Text(stockPicking.batchno ?? '--')),
          DataCell(Text(stockPicking.createUid ?? '--')),
          DataCell(Text(Utils.timeUTC(stockPicking.createDate))),
          DataCell(Text(stockPicking.locationName ?? '--')),
          DataCell(Text(stockPicking.locationDestName ?? '--')),
          DataCell(Text(stockPicking.pickingTypeName ?? '--')),
          DataCell(Text(stockPicking.productorderno ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
            label: "订单领料",
            iconData: Icons.view_headline,
            onPressed: () => _workshopPicking()),
        CryButton(
            label: "批量出库",
            iconData: Icons.view_headline,
            onPressed: () => _batchOut()),
        CryButton(
            label: "批量退货",
            iconData: Icons.view_headline,
            onPressed: () => _batchReturn()),
        CryButton(
          label: "查看明细",
          iconData: Icons.view_headline,
          onPressed: selectedList.length == 1
              ? () => _openDetail(selectedList[0])
              : null,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _workshopPicking() {
    Utils.fullscreenDialog(ProductionOrderQuery());
  }

  _batchOut() {
    Utils.fullscreenDialog(ProductOdoData());
  }

  _batchReturn() {
    Utils.fullscreenDialog(ProductOdoData(isReturn: true));
  }

  _openDetail(StockPicking stockPicking) {
    Utils.fullscreenDialog(StockProductionList(
      stockPicking: stockPicking,
      flag: false,
    ));
  }

  _reset() {
    stockPicking = StockPicking();
    formKey.currentState!.reset();
    if (userInfo.major != null) {
      locationIdList = [];
    }
    stockPicking.createDateStart = Utils.getDate();
    stockPicking.createDateEnd = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await StockPickingOdooApi.workshopPickingPage(data: {
      "page": page,
      "domainList": stockPicking.toWorkshopPickingDomainList()
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: WorkshopPickingDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockPicking = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockPicking>((e) => StockPicking.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          // _openDetail();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('产品信息'),
          ),
        ),
      ],
    );
  }
}
